from flask import Blueprint,request,make_response,redirect,jsonify
from application.models.users.user import *
from utils.captcha.captcha import captcha
from utils.myredis import r
import redis

from utils.myjwt import myjwt
from qiniu import Auth

cc_blue = Blueprint("ccbule",__name__)


@cc_blue.route("/gettags")
def gettags():
    tags=Tags.query.all()
    tagslist=[{"id":i.id,"name":i.name} for i in tags]
    types=Ctype.query.all()
    typelist=[{"id":i.id,"name":i.name} for i in types]
    ctype=CourseType.query.all()
    clist=[{"id":i.id,"name":i.name} for i in ctype]
    return jsonify({"code":200,"tags":tagslist,"types":typelist,"clist":clist})


@cc_blue.route("/qniu")
def qniu():
    access_key = 'wTNsEnBS4nj89eJjYUSaMt-YK-459dnvuIMBv4k5'
    secret_key = '2xt_JPXSj37yqle1fMLaEAEpn-K_E8Gyuj4Tcr8H'
    q = Auth(access_key, secret_key)
    #要上传的空间
    bucket_name = 'h2203ab'
    #生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name)
    return  jsonify({'code':200,'token':token})



import json

@cc_blue.route("/addcouse",methods=['POST'])
def addcourse():
    try:
        data=json.loads(request.data)
        course=Course(name=data['name'],url=data['url'],descrip=data['desc'],ctype=data['type'])
        db.session.add(course)
        scourse=Course.query.filter(Course.name==data['name']).first()
        for i in data['tags']:
            sql="insert into course_tag(courseid, tagid) values(%d,%d)"%(scourse.id,int(i))
            db.session.execute(sql)
            for i in data['ctype']:
                sql1="insert into course_cate(courseid, course_typeid) values(%d,%d)"%(scourse.id,int(i))
                db.session.execute(sql1)
            db.session.commit()
    except:
        db.session.rollback()
    return jsonify({"code": 200, "msg": "添加成功"})


import math
# @cc_blue.route("/getCourse")
# def getCourse():
#     page=int(request.args.get("page"))
#
#     online=int(request.args.get("is_publish"))
#     total=Course.query.filter(Course.is_publish==online).count()
#     page_size=2
#     start=math.ceil((page-1)*page_size)
#     orderpara=request.args.get("orderpara")
#     if orderpara == 'new':
#         course=Course.query.order_by(Course.create_time.desc()).filter(Course.is_publish==online).offset(start).limit(page_size).all()
#     else:
#         course=Course.query.order_by(Course.views.desc()).filter(Course.is_publish==online).offset(start).limit(page_size).all()
#     list=[{"id":i.id,"name":i.name,"url":i.url,"views":i.views} for i in course]
#     return jsonify({"code":200,"clist":list,"total":total,"page_size":page_size})




#类别
@cc_blue.route("/ctype")
def ctype():
    ctypelist = []
    # 获取缓存中数据
    r.del_key("ctype")
    ctype = r.str_get("ctype")
    # 判断是否存在
    if ctype:
        ctypelist = json.loads(ctype)
    else:
        sql = Ctype.query.all()
        for i in sql:
            d = {
                "id": i.id,
                "name":i.name
            }
            ctypelist.append(d)
        # 存入缓存
        r.str_add("ctype", json.dumps(ctypelist))
    return ctypelist




# 标签
def getTaglist():
    taglist = []
    r.del_key("tage")
    tag = r.str_get("tage")
    if tag:
        taglist = json.loads(tag)
    else:
        sql = Tags.query.all()
        for i in sql:
            d = {
                "id":i.id,
                "name":i.name
            }
            taglist.append(d)
        r.str_add("tage", json.dumps(taglist))
    return taglist




@cc_blue.route("/getHomeGourse")
def getHomeGourse1():
    # 获取类型
    ctypelist = ctype()
    # 获取标签
    taglist = getTaglist()
    # 获取当前页面
    page = request.args.get("page")
    # 获取查询条件
    typeid = request.args.get("type")
    tagid = request.args.get("tagid")
    online = request.args.get("online")
    # 排序条件
    orderbyid = request.args.get("orderbyid")

    where = ""
    if int(typeid) > 0:
        where = where + " and c.ctype=" + typeid

    if int(online) > 0:
        where = where + " and c.views=" + online

    # res = db.session.execute("select * from user where id=1")
    # print(res.fetchall())
    # print(res.fetchone())

    if int(tagid) > 0:
        tsql = "select count(c.id) as tcount from course as c inner join course_tag as cl on cl.courseid=tcount where cl.tagid=" + tagid
        sql = "select * from course as c inner join course_tag as cl on cl.courseid=c.id  where cl.tagid=" + tagid
    else:
        sql = "select * from course as c where 1=1"
        tsql = "select count(c.id) as tcount from course as c  where 1=1"

    if where:
        sql = sql + " " + where
        tsql = tsql + " " + where

    if int(orderbyid) > 0:
        if int(orderbyid) == 1:
            sql = sql + " order by c.id desc"
        else:
            sql = sql + " order by c.is_publish desc"

    # 查询总共有多少条
    tsql = db.session.execute(tsql)
    total = 0
    for i in tsql:
        total = i[0]

    page_size = 2
    start = (int(page) - 1) * page_size
    clist = sql + " limit %d,%d" % (start, page_size)
    clist = db.session.execute(clist)
    courselist = []
    for i in clist:
        d = {
            "id":i[0],
            "create_time":i[1],
            "update_time":i[2],
            "name":i[3],
            "url":i[4],
            "descrip":i[5],
            "tcount":i[6],
            "views":i[7],
            "is_publish":i[8],
            "ctype":i[9],
            "buy":i[10]
        }
        courselist.append(d)
        print("cccccccccccccccc",courselist)

    return jsonify({"code": 200, "tlist": ctypelist, 'taglist': taglist, 'clist': courselist, "total": total,
                    "page_size": page_size})






# 课程详情页面
@cc_blue.route("/detail")
def detail():
    # 获取课程id
    id = request.args.get('id')
    # 从缓存中查询课程及章节信息
    key = "course"+str(id)
    skey = "jie"+str(id)
    r.del_key(key)
    r.del_key(skey)
    course = r.str_get(key)
    if course:
        print("缓存")
        jie = r.str_get(skey)
        return jsonify({"code": 200, 'clist': json.loads(course), 'slist': json.loads(jie)})
    # 如果存在直接返回，如果不存在查询数据库
    else:
        print("查询")
        sql = "select c.id,j.id as jid,c.name as cname,c.descrip,c.tcount,j.name,j.url,j.type,c.ctype from course as c inner join jie as j on c.id=j.courseid where c.id=%d order by j.tcount asc" % (
            int(id))
        res = db.session.execute(sql)
        jie = []
        course = []
        for i in res:
            # 获取课程下所有的章节
            d = {
                "id": i['jid'], "name": i['name'], "url": i['url'], "courseid": i['id'], "type": i['type']
            }
            # 获取课程信息
            c = {
                "id": i['id'], "type": i["ctype"], "name": i['cname'],
                'descrip': i['descrip'], 'tcount': i['tcount']
            }
            jie.append(d)
            course.append(c)
        # 数据解析存入redis
        r.str_add(key, json.dumps(course))
        r.str_add(skey, json.dumps(jie))
        return jsonify({"code": 200, 'clist': course, 'slist': jie})


@cc_blue.route("/getVideo")
def getVideo():
    # 获取用户id和章节id
    courseid = request.args.get("courseid")
    userid = request.args.get("userid")
    id = request.args.get("id")
    # 通过用户表查询用户级别
    sql = "select level from user where id=%d"%(int(userid))
    user = db.session.execute(sql)
    # 通过课程id查询课程的类型
    key = "jie"+str(courseid)
    course = r.str_get(key)
    if course:
        course=json.loads(course)
        for i in course:
            ctype=i["type"]
            if int(ctype) == 2:
                # 会员可看
                for j in user:
                    user = j["level"]
                    if int(user) != 2:
                        return jsonify({"code": 10011, "msg":"此用户没有权限观看"})
                    # 课程type=3  需要购买课程
            if int(ctype) == 3:
                bsql = "select * from vipuser_course where userid=%d and courseid=%d"%(int(userid),int(courseid))
                bres = db.session.execute(bsql)
                if not bres:
                    return jsonify({"code": 10012, "msg":"此课程需要单独购买"})
            # 获取此课程下的所有章节
            skey = "jie"+str(courseid)
            jie = json.loads(r.str_get(skey))
            for i in jie:
                if int(i["id"]) == int(id):
                    url = i["url"]
            # 返回此章节播放的url
            return jsonify({"code": 200, "msg":"获取成功", "url":url})
    else:
        return jsonify({"code":10010})


import time
import random
from utils.conn import get_ali_object

@cc_blue.route("/addshopp")
def addshopp():
    data = json.loads(request.data)
    gid = int(data['gid']) #课程id
    sum = int(data['sum']) #购买的数量
    uid = int(data['userid'])

    # 获取改商品的全部信息
    comsql = "select * from tcourse where id=%d" % (gid)
    cres = db.execute(comsql)
    print(cres)
    goods_name = cres['name']
    goods_price = float(cres['price'])
    total = sum * int(float(cres['price']))
    number = str(int(time.time())) + str(uid) + str(random.randint(100000, 999999))
    times = datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%M:%S")

    # try:
        # 订单编号

    sql = "select lock_store from tcourse where id=%d and inventory-lock_store>=%d" % (gid, sum)
    res = db.session.execute(sql)
    print(res)
    if res:
        # 锁定库存
        # try:
        # 订单号、用户id、课程id、数量、单价、总价格、状态、支付宝流水号
                  # 写入订单表
        csql = "insert into orders(order_no ,courseid,userid,number,price,tmoney,status,trans_no)values ('%s','%d','%d',%d,'%f','%f',%d,'%s') " % (number,gid,uid,sum,goods_price,total,int(1),number)
        db.session.execute(csql)
        # 更新锁定库存

        # lock = int(cres['inventory']) - sum #锁定
        # zong = int(cres['lock_store'])+sum
        sql1 = "update tcourse set store=%d where id=%d" % (sum,gid)
        db.session.execute(sql1)
        db.session.commit()
        # except:
        #     db.rollback()
    alipay = get_ali_object()
    query_params = alipay.direct_pay(
        subject=str(uid) + "购买训练营课程",  # 商品简单描述
        out_trade_no=number,  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=total,  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
# 把订单号写入延时队列当中
# pkey = 'orderpayfailorder1'
# r.sortedset_add(pkey, number, int(time.time()))
    return jsonify({
        'code': 200,
        'url': pay_url
    })


from flask_restful import reqparse
#添加购物车
@cc_blue.route("/addcart",methods=['POST'])
def addcart():
    data = reqparse.RequestParser()
    data.add_argument("userid")
    data.add_argument("goodsid")
    args = data.parse_args()
    userid = int(args["userid"])
    goodsid = int(args["goodsid"])
    # pkey = "mycart" + str(userid)
    # r.hash_add(pkey,goodsid,userid)
    # return jsonify({"code":200,"msg":"添加购物车成功"})
    pkey = "mycart"+str(userid)
    r.hash_add(pkey,goodsid,userid)
    return jsonify({"code":200,"msg":"加入购物车成功"})


# 我的购物车
@cc_blue.route("/getcart")
def getcart():
    userid = request.args.get("userid")
    pkey = "mycart"+str(userid)
    print(pkey)
    res = r.hash_getall(pkey)
    print(">>>",res)
    cartlist = []
    for i,j in res.items():
        goodsid = i.decode()
        sql = "select id,name,price,url from course where id=%d"%int(goodsid)
        res = db.session.execute(sql)
        for i in res:
            cartlist = {"id":i["id"],"name":i["name"],"price":i["price"],"url":i["url"]}
        print(cartlist)
        return jsonify({"code": 200, "msg":"ok","cartlist": cartlist})




from utils.conn import get_ali_object
@cc_blue.route("/pay",methods=["POST"])
def pay():
    data=json.loads(request.data)
    userid=int(data["userid"])
    courseid=int(data["courseid"])
    sum=0
    sql = "select * from course where id=%d" % courseid
    print(sql)
    res=db.session.execute(sql)
    print("res>>",res)
    for i in res:
        cartlist = {"id": i['id'],
        "create_time": i['create_time'],
        "update_time": i['update_time'],
        "name": i['name'],
        "url": i['url'],
        "descrip": i['descrip'],
        "tcount": i['tcount'],
        "views": i['views'],
        "is_publish": i['is_publish'],
        "ctype": i['ctype'],
        "buy": i['buy'],
        "price":i["price"]}
    print(cartlist)
    sum+=float(cartlist["price"])
    # 订单号
    number = str(userid) + str(random.randint(1000, 9999))
    create_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
    update_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
    status = 2
    # try:
    usql = Vipuser_course(courseid=courseid,userid=userid)
    db.session.add(usql)
    print(usql.userid,usql.courseid,"oooooo")
    isql = Orders(create_time=create_time,update_time=update_time,userid=userid,courseid=courseid,number=number,tmoney=sum,status=status)
    db.session.add(isql)
    db.session.commit()
    # except:
    #     db.session.rollback()
    # 支付
    alipay = get_ali_object()
    query_params = alipay.direct_pay(
        subject=str(userid) + "购买课程",  # 商品简单描述
        out_trade_no=number,  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=sum,  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({
        'code': 200,
        'url': pay_url
    })
@cc_blue.route("/callback")
def callback():
    try:
        sql = "update orders set status=2"
        db.session.add(sql)
        db.session.commit()
    except:
        db.session.rollback()
    # 跳转到个人中心
    return redirect('http://localhost:8080/#/courr')